package com.zzg.datastructure.linkedlist;

/**
 * @Author zhengzg
 * @Date 2022-08-17
 * @Version v1.0
 */
public class DoubleLinkedList {

    private final HeroNode2 head = new HeroNode2(0,"","");

    public HeroNode2 getHead() {
        return head;
    }

    // 遍历双向链表方法
    public void list(){
        if (head.next == null){
            return;
        }

        HeroNode2 temp = head.next;
        while (temp != null){
            System.out.println(temp);
            temp = temp.next;
        }
    }

    // 添加一个节点到双向链表的最后
    public void add(HeroNode2 heroNode2){
        HeroNode2 temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }

        temp.next = heroNode2;
        heroNode2.pre = temp;
    }

    // 修改节点内容
    public void update(HeroNode2 heroNode2){
        if (head.next == null){
            System.out.println("链表为空");
            return;
        }

        HeroNode2 temp = head.next;
        boolean flag = false;
        while (true){
            // 遍历到最后
            if (temp == null){
                break;
            }

            if (temp.no == heroNode2.no){
               flag = true;
               break;
            }

            temp = temp.next;
        }

        if (flag) {
            temp.name = heroNode2.name;
            temp.nickName = heroNode2.nickName;
        }else {
            System.out.println("没有找到该节点");
        }
    }

    // 双向链表删除
    public void del(int no){
        if (head.next == null){
            System.out.println("链表为空");
            return;
        }

        HeroNode2 temp = head.next;
        boolean flag = false;

        while (true){
            if (temp == null){
                break;
            }
            if (temp.no == no){
                flag = true;
                break;
            }
            temp = temp.next;
        }

        if (flag){
            temp.pre.next = temp.next;
            // 因为删除最后一个节点时next为null，会出现空指针异常，需要进行判断
            if (temp.next != null){
                temp.next.pre = temp.pre;
            }
        }else {
            System.out.println("要删除的节点不存在");
        }
    }

}
